﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ShareYou.Message.Enum;
using ShareYou.Message.InterFace;
using ShareYou.Message.Model;

namespace ShareYou.Message.Framework
{
    /// <summary>
    /// 消息发送的基类,消息
    /// </summary>
    public abstract class MessageSender<TMessage,TEntity,TResult>
        where TMessage:BaseMessage
        where TEntity:class
        where TResult:class
    {
        private readonly IEntitySerialized<TEntity,TResult> _serializer;

        /// <summary>
        ///构造:指定对应的序列化对象
        /// </summary>
        /// <param name="serializer"></param>
        protected MessageSender(IEntitySerialized<TEntity,TResult> serializer)
        {
            this._serializer = serializer;
        }
        /// <summary>
        /// 消息发送的Url地址
        /// </summary>
        public abstract string Url { get; }

        /// <summary>
        /// 设置请求发送方式
        /// </summary>
        public abstract MessageSendMethodType Type { get; }

        public abstract string ContentType { get; }


        public abstract string UserAgent { get; }

        public abstract void SetHttpHeader(WebHeaderCollection header);//请求的标题头

        /// <summary>
        /// 发送指定消息的操作
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual TResult SendMessage(TEntity entity)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest) WebRequest.Create(this.Url);
            req.Method=this.Type.ToString();
            //设置请求头部
            this.SetHttpHeader(req.Headers);
            req.ContentType = this.ContentType;
            req.UserAgent = this.UserAgent;
            req.ReadWriteTimeout = 30000;
            byte[] reqBuffer = Encoding.UTF8.GetBytes(this._serializer.Serialized(entity));
            using (Stream stream=req.GetRequestStream())
            {
                stream.WriteTimeout = 30000;
                stream.Write(reqBuffer,0,reqBuffer.Length);
                stream.Close();
            }
            using (HttpWebResponse rep = (HttpWebResponse) req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(rep.GetResponseStream(), Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            //开始反序列化
            TResult tResult = this._serializer.DeSerailized(result);
            return tResult;
        }


    }


    
}
